//
//  TYZIndicatorView.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/29.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "TYZIndicatorView.h"
#define IndicatorViewCollectionViewItemID              @"TYZIndicatorViewCollectionItemID"
#define IndicatorViewCollectionViewLableWidthPadding   20
#define IndicatorViewCollectionViewLableHeightPadding  15

@implementation TYZIndicatorModel
- (UIColor *)selectedTextColor {
    if (_selectedTextColor == nil) {
        _selectedTextColor = TYZWhiteColor;
    }
    return _selectedTextColor;
}
- (UIColor *)normalTextColor {
    if (_normalTextColor == nil) {
        _normalTextColor = TYZLightColor;
    }
    return _normalTextColor;
}
- (UIColor *)borderColor {
    if (_borderColor == nil) {
        _borderColor = TYZLightColor;
    }
    return _borderColor;
}
- (UIColor *)selectedColor {
    if (_selectedColor == nil) {
        _selectedColor = ThemeColor;
    }
    return _selectedColor;
}
- (UIColor *)normalColor {
    if (_normalColor == nil) {
        _normalColor = TYZWhiteColor;
    }
    return _normalColor;
}
- (UIFont *)font {
    if (_font == nil) {
        _font = TYZFont(CoreInfo.fontSize);
    }
    return _font;
}
@end

@interface TYZIndicatorView ()<UICollectionViewDelegate, UICollectionViewDataSource>
/**
 *  CollectionView
 */
@property(nonatomic, strong) TYZCollectionView *collectionView;
/**
 *  每个标签的高度
 */
@property(nonatomic, assign) CGFloat aLabelHeight;
/**
 *  记录偏移量
 */
@property (assign, nonatomic) CGPoint lastContentOffset;
@end

@implementation TYZIndicatorView

/**
 创建指示器，默认是单个选择的指示器
 
 @param textArray 文本内容
 @return 指示器
 */
+ (instancetype)indicatorWithTextArray:(NSArray<NSString *> *)textArray {
    TYZIndicatorModel *model = [[TYZIndicatorModel alloc] init];
    model.singleton = YES;
    return [self indicatorWithTextArray:textArray dataModel:model];
}

/**
 创建指示器
 
 @param textArray 文本内容
 @param dataModel 数据模型
 @return 指示器
 */
+ (instancetype)indicatorWithTextArray:(NSArray<NSString *> *)textArray dataModel:(TYZIndicatorModel *)dataModel {
    TYZIndicatorView *indicatorView = [[TYZIndicatorView alloc] init];
    indicatorView.textArray = textArray;
    indicatorView.model = dataModel;
    return indicatorView;
}
- (instancetype)init {
    if (self = [super init]) {
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:IndicatorViewCollectionViewItemID];
    }
    return self;
}
#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.textArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:IndicatorViewCollectionViewItemID forIndexPath:indexPath];
    [cell.contentView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    TYZLabel *label = [[TYZLabel alloc] init];
    label.text = self.textArray[indexPath.item];
    [cell.contentView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.contentView);
    }];
    label.font = self.model.font;
    label.textColor = TYZLightColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.cornerRadius = (self.aLabelHeight + IndicatorViewCollectionViewLableHeightPadding) * 0.5;
    label.layer.masksToBounds = YES;
    if (self.model.singleton) {
        if (self.model.itemNumber == indexPath.item) {
            label.textColor = self.model.selectedTextColor;
            label.backgroundColor = self.model.selectedColor;
        } else {
            label.textColor = self.model.normalTextColor;
            label.backgroundColor = self.model.normalColor;
        }
    } else {
        __block BOOL isTint = NO;// 是否被渲染
        [self.model.itemNumberArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj integerValue] == indexPath.item) {
                label.layer.borderWidth = 0;
                label.textColor = self.model.selectedTextColor;
                label.backgroundColor = self.model.selectedColor;
                isTint = YES;
                *stop = YES;
            }
        }];
        if (isTint == NO) {
            label.layer.borderWidth = 1;
            label.layer.borderColor = self.model.borderColor.CGColor;
            label.textColor = self.model.normalTextColor;
            label.backgroundColor = self.model.normalColor;
        }
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = [self.textArray[indexPath.item] getSizeWithFont:self.model.font];
    return CGSizeMake(size.width + IndicatorViewCollectionViewLableWidthPadding, self.aLabelHeight + IndicatorViewCollectionViewLableHeightPadding);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger )section {
    return UIEdgeInsetsMake (0 ,10 ,0 ,10 );
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.lastContentOffset = collectionView.contentOffset;
    if (self.model.singleton) {
        if (self.model.itemNumber != indexPath.item) {
            self.model.itemNumber = indexPath.item;
            TYZSelectedModel *model = [[TYZSelectedModel alloc] init];
            model.number = indexPath.item;
            model.name = self.textArray[indexPath.item];
            if (self.didSelectedItemBlock) {
                self.didSelectedItemBlock(@[model]);
            }
        }
    } else {
        NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.model.itemNumberArray];
        // 是否存在
        __block BOOL isExit = NO;
        // 如果点击了选择的，那么不选择
        [self.model.itemNumberArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj integerValue] == indexPath.item) {
                [arrM removeObject:obj];
                isExit = YES;
                *stop = YES;
            }
        }];
        if (isExit == NO) {
            // 如果点击未选择的，那么选择它
            [arrM addObject:@(indexPath.item)];
        }
        self.model.itemNumberArray = [arrM mutableCopy];
        if (self.didSelectedItemBlock) {
            NSMutableArray *modelArrM = [NSMutableArray arrayWithCapacity:arrM.count];
            [self.model.itemNumberArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                TYZSelectedModel *model = [[TYZSelectedModel alloc] init];
                model.number = [obj integerValue];
                model.name = self.textArray[model.number];
                [modelArrM addObject:model];
            }];
            self.didSelectedItemBlock([modelArrM mutableCopy]);
        }
    }
    [self.collectionView reloadData];
    collectionView.contentOffset = self.lastContentOffset;
}
#pragma mark - setter & getter
- (TYZCollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        // 同一行相邻两个cell的最小间距
        layout.minimumInteritemSpacing = 5;
        // 横向滑动
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[TYZCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}
- (void)setTextArray:(NSArray<NSString *> *)textArray {
    _textArray = textArray;
    [self refreshCollectionView];
}
- (void)setModel:(TYZIndicatorModel *)model {
    _model = model;
    [self refreshCollectionView];
}
- (void)refreshCollectionView {
    if (self.textArray && self.model) {
        self.aLabelHeight = [self.textArray.firstObject getSizeWithFont:self.model.font].height;
        [self.collectionView reloadData];
    }
}
@end
